using System;
using System.Collections.Generic;
using CMS_Admin.Backend.Api.Entity;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using CMS_Admin.Backend.Api.ParamModel;
using Newtonsoft.Json;
using CMS_Admin.Backend.Api.Repository;
using CMS_Admin.Backend.Api.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Authentication;

namespace CMS_Admin.Backend.Controllers
{
    /// <summary>
    /// 文章管理
    /// </summary>

    [Authorize]
    [ApiController]
    [Route("article")]
    public class ArticleController : ControllerBase
    {
        private IRepository<Articles> _articleRespository;
        private IRepository<ArticleClass> _articleClass;
        private IRepository<UserArticles> _userArticles;
        private IRepository<Likes> _likes;
        private IRepository<Comments> _comments;
        private IRepository<Resource> _resource;
        private IRepository<Users> _users;

        private IWebHostEnvironment _env;




        private readonly IConfiguration _configuration;

        public ArticleController(IConfiguration configuration, IWebHostEnvironment webHostEnvironment, IRepository<Articles> articleRespository, IRepository<ArticleClass> articleClass, IRepository<Resource> resource, IRepository<Users> users, IRepository<Comments> comments, IRepository<UserArticles> userArticles, IRepository<Likes> likes)
        {
            _configuration = configuration;
            _env = webHostEnvironment;
            _articleRespository = articleRespository;
            _articleClass = articleClass;
            _resource = resource;
            _users = users;
            _likes = likes;
            _comments = comments;
            _userArticles = userArticles;

        }
        /// <summary>
        /// 查找所有文章
        /// </summary>
        /// <param name="pager"></param>
        /// <returns></returns>
        [HttpGet]
        public dynamic Get([FromQuery] Pager pager)
        {
            var pageIndex = pager.PageIndex;
            var pageSize = pager.PageSize;

            var comment = from comments in _comments.Table

                          group comments by new { comments.ArticlesId }
                           into g
                          select new { ArticlesId = g.Key.ArticlesId, Count = g.Count() };


            var like = from likes in _likes.Table
                       where likes.Liked == true
                       group likes by new { likes.ArticlesId }

                       into l
                       select new { ArticlesId = l.Key.ArticlesId, Count = l.Count() };


            System.Console.WriteLine(comment);

            var article = from articles in _articleRespository.Table
                          join artcleclasses in _articleClass.Table on articles.ArticleClassId equals artcleclasses.Id
                          join userArticles in _userArticles.Table on articles.Id equals userArticles.ArticlesId
                          join user in _users.Table on userArticles.UserId equals user.Id
                          join resoure in _resource.Table on articles.ResourceId equals resoure.Id

                          orderby articles.Id
                          where articles.IsDeleted == false
                          select new
                          {
                              Id = articles.Id,
                              Username = user.Username,
                              articleTitle = articles.ArticleTitle,
                              Content = articles.Content,
                              redaNumber = articles.ReadNumber,
                              articlesClsssName = artcleclasses.ArticleClassName,
                              CreatedTime = articles.CreatedTime,
                              ResoutceName = resoure.ResoutceName
                          };


            // var c = comment.Count();
            // 对获得的记录分页
            var u = article.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            // // 返回的数据里，带有数据和分页信息
            var res = new
            {
                Code = 200,
                Data = new
                {
                    Data = u,
                    comment = comment.ToList(),
                    like = like.ToList(),
                    Pager = new
                    {
                        pageIndex,
                        pageSize,
                        rowsTotal = article.Count(),
                    }
                },
                Msg = "获取文章列表成功^_^"
            };
            return JsonHelper.Serialize(res);
        }






        /// <summary>
        /// 根据指定id查找文章
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("{id}")]
        public dynamic Get(int id)
        {
            var article = _articleRespository.GetById(id);
            var articleClass = _articleClass.Table.Where(ac => ac.Id == article.ArticleClassId).FirstOrDefault();
            var resource = _resource.Table.Where(rc => rc.Id == article.ResourceId).FirstOrDefault();

            article.ArticleClass = articleClass;
            article.Resource = resource;



            var like = from likes in _likes.Table
                       where likes.Liked == true && likes.ArticlesId == id
                       select likes;

            var isLogin = base.HttpContext.AuthenticateAsync().Result.Principal;

            dynamic islike;

            if (isLogin != null)
            {
                var claims = base.HttpContext.AuthenticateAsync().Result
                            .Principal.Claims.FirstOrDefault().Subject.Claims;

                var userid = claims.FirstOrDefault(c => c.Type == "id")?.Value;
                islike = _likes.Table.Where(i => i.UsersId == int.Parse(userid) && i.Liked == true && i.ArticlesId == id).FirstOrDefault();

            }
            else
            {
                islike = null;
            }





            if (article == null)
            {
                return new
                {
                    Code = 1004,
                    Data = "",

                    Msg = "指定文章不存在"
                };

            }

            return JsonHelper.Serialize(new
            {
                Code = 200,
                Data = article,
                like = like.Count(),
                Liked = islike == null ? false : true,
                Msg = "获取文章列表成功^_^"
            });

        }
        /// <summary>
        /// 添加文章
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public string Post(NewArticle model)
        {


            var articleTitle = model.ArticleTitle.Trim();
            var content = model.Content.Trim();
            var readNumber = 0;
            // var articleClassName = model.ArticleClassName.Trim();
            // var thumbUpNumber = model.ThumbUpNumber;
            var articleClassId = _articleClass.Table.Single(ac => ac.ArticleClassName == model.ArticleClassName).Id;
            var resourceId = _resource.Table.Where(ac => ac.ResoutceName == model.ResoutceName).FirstOrDefault() == null
             ? 1 : _resource.Table.Single(ac => ac.ResoutceName == model.ResoutceName).Id;




            if (string.IsNullOrEmpty(articleTitle))
            {
                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "文章标题不能为空，请确认后重试"
                };
                return JsonHelper.Serialize(tmp);
            }


            var newArticle = new Articles
            {
                ArticleTitle = articleTitle,
                Content = content,
                ReadNumber = readNumber,
                // ThumbUpNumber = thumbUpNumber,
                ArticleClass = _articleClass.Table.Single(a => a.Id == articleClassId),
                Resource = _resource.Table.Single(s => s.Id == resourceId)

            };

            _articleRespository.Insert(newArticle);


            var claims = base.HttpContext.AuthenticateAsync().Result
          .Principal.Claims.FirstOrDefault().Subject.Claims;


            var userid = claims.FirstOrDefault(c => c.Type == "id")?.Value;

            _userArticles.Insert(new UserArticles
            {

                User = _users.Table.Single(u => u.Id == int.Parse(userid)),
                Articles = _articleRespository.Table.Single(b => b.Id == newArticle.Id)
            });

            var res = new
            {
                Code = 200,
                Data = newArticle,
                Msg = "创建文章成功"
            };
            return JsonHelper.Serialize(res);
        }

        /// <summary>
        /// 修改指定文章
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public dynamic Put(int id, NewArticle model)
        {
            var artic = _articleRespository.GetById(id);

            if (artic != null)
            {
                var articleClassId = _articleClass.Table.Single(ac => ac.ArticleClassName == model.ArticleClassName).Id;
                var resourceId = _resource.Table.Where(ac => ac.ResoutceName == model.ResoutceName).FirstOrDefault() == null
                 ? 1 : _resource.Table.Single(ac => ac.ResoutceName == model.ResoutceName).Id;

                artic.ArticleTitle = model.ArticleTitle;
                artic.Content = model.Content;
                artic.ArticleClass = _articleClass.Table.Single(a => a.Id == articleClassId);
                artic.Resource = _resource.Table.Single(s => s.Id == resourceId);

                // artic.ReadNumber = model.ReadNumber;
                // artic.ThumbUpNumber = model.ThumbUpNumber;
                artic.UpdatedTime = DateTime.Now;


                _articleRespository.Update(artic);


                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = artic,
                    Msg = string.Format("你修改的用户的id为：{0}，已经修改成功，请注意查收", id)
                });
            }
            else
            {
                return JsonHelper.Serialize(new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "指定Id的用户不存在，请确认后重试"
                });
            }
        }
        /// <summary>
        /// 删除指定文章
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {
            var user = _articleRespository.GetById(id);
            if (user != null)
            {
                _articleRespository.Delete(id);
                return new
                {
                    Code = 200,
                    Msg = string.Format("删除指定id为{0}的文章成功", id)
                };
            }
            else
            {
                return new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "指定Id的文章不存在，请确认后重试"
                };
            }

        }


    }
}